package com.xmcitypower.keycabinet.generaledition;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.security.keystore.KeyInfo;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.xmcitypower.keycabinet.generaledition.com485.SendOrderTo485Manager;
import com.xmcitypower.keycabinet.generaledition.com485.SerialManager;
import com.xmcitypower.keycabinet.generaledition.db.Bean.DB_KeyBorrowInfo;
import com.xmcitypower.keycabinet.generaledition.db.Bean.DB_KeyInfo;
import com.xmcitypower.keycabinet.generaledition.db.Bean.DB_Single_UserInfo;
import com.xmcitypower.keycabinet.generaledition.db.impl.KeyBorrowInfoDaoImp;
import com.xmcitypower.keycabinet.generaledition.db.impl.KeyInfoDaoImp;
import com.xmcitypower.keycabinet.generaledition.excption.MyCrashHandler;
import com.xmcitypower.keycabinet.generaledition.utils.LogUtil;
import com.za.finger.MainFingerActivity;
import com.xmcitypower.keycabinet.generaledition.common.Constants;
import com.xmcitypower.keycabinet.generaledition.db.impl.SingleUserInfoDaoImp;
import com.xmcitypower.keycabinet.generaledition.dialog.CustomDialog;
import com.xmcitypower.keycabinet.generaledition.listener.SdkInitListener;
import com.xmcitypower.keycabinet.generaledition.manager.FaceSDKManager;
import com.xmcitypower.keycabinet.generaledition.register.FaceNIRAttendanceActivity;
import com.xmcitypower.keycabinet.generaledition.utils.OtherUtil;
import com.xmcitypower.keycabinet.generaledition.utils.PrefUtils;
import com.xmcitypower.keycabinet.generaledition.utils.TimeUtils;
import com.xmcitypower.keycabinet.generaledition.utils.ToastUtils;
import com.example.zazjni.ZAZJni;

import org.apache.log4j.chainsaw.Main;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sunshine on 2020/7/6.
 * 单机版主页
 */

public class MainActivity extends MainFingerActivity {
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_date)
    TextView tvDate;

    LinearLayout ll_bg;
    private static int settingcount = 0;
    @BindView(R.id.tv_cabinet)
    TextView tvCabinet;
    //private On485DataListener on485DataListener;
    private Timer timer;

    private CustomDialog commitDialog3;
    private TextView btn_cancel3;
    private TextView btn_confirm3;

    private CustomDialog commitDialog2;
    private TextView btn_cancel2;
    private TextView btn_confirm2;

    private CustomDialog commitDialog;
    private TextView btn_confirm;
    private TextView tv_delete;

    private int jjcount = 300;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initListener();

        initTimer();

        SerialManager.getInstance().init(ExpressApp.getInstance());

        //设置该类为系统默认处理类
        MyCrashHandler.newInstance().init(this);

        OnOpenDeviceBtnZazNew();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.e("屏幕指纹", "identify");
                    OnIdentifyBtnZazNew();
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "请安装指纹模块", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();

        //更新时间
        tvTime.setText(TimeUtils.getTimeShort(new Date()));
        tvDate.setText(TimeUtils.getStringDateShort(new Date()) + " " + TimeUtils.getWeek(new Date()));

    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                //更新时间
                tvTime.setText(TimeUtils.getTimeShort(new Date()));
                tvDate.setText(TimeUtils.getStringDateShort(new Date()) + " " + TimeUtils.getWeek(new Date()));
            }
        }
    };

    private void initTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                String curTime = OtherUtil.getTime();
                if (curTime.contains("03:00:00")) {
                    LogUtil.getInstance().info("每日清空一年以上借用记录" + curTime);
                    ArrayList<DB_KeyBorrowInfo> db_keyBorrowInfos = KeyBorrowInfoDaoImp.getInstance(MainActivity.this).getAllInfos();
                    for (int i = 0; i < db_keyBorrowInfos.size(); i++) {
                        if((System.currentTimeMillis() - db_keyBorrowInfos.get(i).getBorrowTime()) > 365*24*60*60*1000) {
                            KeyBorrowInfoDaoImp.getInstance(MainActivity.this).delete(db_keyBorrowInfos.get(i));
                        }
                    }
                }

            }
        }, 0, 30000);
    }

    private void initListener() {
        IntentFilter filter = new IntentFilter();//创建意图过滤器对象
        filter.addAction(Intent.ACTION_TIME_TICK);//为接收器指定action，使之用于接收同action的广播
        registerReceiver(receiver, filter);//动态注册广播接收器

        if (FaceSDKManager.initStatus != FaceSDKManager.SDK_MODEL_LOAD_SUCCESS) {
            FaceSDKManager.getInstance().initModel(this, new SdkInitListener() {
                @Override
                public void initStart() {
                }

                @Override
                public void initLicenseSuccess() {
                }

                @Override
                public void initLicenseFail(int errorCode, String msg) {
                }

                @Override
                public void initModelSuccess() {
                    ToastUtils.toast(MainActivity.this, "模型加载成功，欢迎使用");
                }

                @Override
                public void initModelFail(int errorCode, String msg) {
                    if (errorCode != -12) {
                        ToastUtils.toast(MainActivity.this, "模型加载失败，请尝试重启应用");
                    }
                }
            });
        }

        ll_bg = findViewById(R.id.ll_setting);
        ll_bg.setOnTouchListener(new OnDoubleClickListener(new OnDoubleClickListener.DoubleClickCallback() {
            @Override
            public void onDoubleClick() {
                OnCloseDeviceBtnZazNew();
                Intent intent = null;
                intent = new Intent(MainActivity.this, PasswordActivity.class);
                intent.putExtra("pwd_type", "setting");
                startActivity(intent);
            }
        }));
        tvCabinet.setOnTouchListener(new OnDoubleClickListener(new OnDoubleClickListener.DoubleClickCallback() {
            @Override
            public void onDoubleClick() {
                OnCloseDeviceBtnZazNew();
                Intent intent = null;
                intent = new Intent(MainActivity.this, PasswordActivity.class);
                intent.putExtra("pwd_type", "edit");
                startActivity(intent);

                /*SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().sendTo485(
                                "F628C53E02CA5E", "0104000003010E07000F", "1D"));*/
            }
        }));
    }

    @OnClick({R.id.rl_face, R.id.tv_time, R.id.tv_restart, R.id.rl_person, R.id.tv_stop_warning, R.id.tv_captain})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.tv_time:
                /*SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().warn(
                                "03", "01", "1a", false));*/

                /*SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().sendTo485(
                                "01", "01", "1a"));

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().sendTo485(
                                "01", "02", "1a"));
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/

                /*SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().sendTo485(
                                "01", "03", "1a"));*/
                /*SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().warn(
                                "03", "01", "1a"));*/
                break;
            case R.id.tv_stop_warning:
                showConfirmDialog2("确认关闭报警？");
                break;
            case R.id.tv_restart:
                showConfirmDialog2("确认重启软件？");
                break;
            case R.id.rl_face:
                if (!initSuccess()) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OnCloseDeviceBtnZazNew();
                    }
                }).start();
                startActivity(new Intent(MainActivity.this, FaceNIRAttendanceActivity.class));
                break;
            case R.id.rl_person:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OnCloseDeviceBtnZazNew();
                    }
                }).start();
                intent = new Intent(MainActivity.this, PwdBorrowActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_captain:
                if (PrefUtils.getBoolean(MainActivity.this, "isCaptainOpen",false)) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            OnCloseDeviceBtnZazNew();
                        }
                    }).start();

                    intent = new Intent(MainActivity.this, KeyManagementActivity.class);
                    startActivity(intent);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                            if (null == commitDialog || !commitDialog.isShowing()) {
                                showConfirmDialog("请联系管理员");
                            }
                        }
                    });
                }
                break;
        }
    }

    private boolean initSuccess() {
        if (FaceSDKManager.getInstance().initStatus == FaceSDKManager.SDK_UNACTIVATION) {
            Toast.makeText(MainActivity.this, "SDK正在加载模型，请稍后再试",
                    Toast.LENGTH_SHORT).show();
            return false;
        }

        if (FaceSDKManager.getInstance().initStatus == FaceSDKManager.SDK_INIT_FAIL) {
            Toast.makeText(MainActivity.this, "SDK初始化失败，请重新激活初始化",
                    Toast.LENGTH_SHORT).show();
            return false;
        }

        if (FaceSDKManager.getInstance().initStatus == FaceSDKManager.SDK_INIT_SUCCESS) {
            Toast.makeText(MainActivity.this, "SDK正在加载模型，请稍后再试",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void showConfirmDialog2(String hint) {
        View view = View.inflate(this, R.layout.dialog_confirm, null);
        initDialogView2(view, hint);
        commitDialog2 = new CustomDialog(this, OtherUtil.dp2px(400), OtherUtil.dp2px(460),
                view, R.style.CustomDialog);
        commitDialog2.show();
    }

    private void initDialogView2(View view, String hint) {
        TextView tvHint = view.findViewById(R.id.tv_hint);
        tvHint.setText(hint);

        btn_cancel2 = view.findViewById(R.id.btn_cancel);

        btn_cancel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog2();
            }
        });

        btn_confirm2 = view.findViewById(R.id.btn_confirm);

        btn_confirm2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog2();

                if (hint.contains("报警")) {
                    /*new Thread(new Runnable() {
                        @Override
                        public void run() {
                            OnCloseDeviceBtnZazNew();
                        }
                    }).start();*/
                    Intent intent = null;
                    intent = new Intent(MainActivity.this, PasswordActivity.class);
                    intent.putExtra("pwd_type", "warn");
                    startActivity(intent);
                } else {
                    OtherUtil.restartApplication(MainActivity.this);
                }
            }
        });
    }

    private void closeDialog2() {
        if (commitDialog2 != null && commitDialog2.isShowing()) {
            commitDialog2.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        PrefUtils.setBoolean(this, "isKeyRegister", false);
        PrefUtils.setBoolean(this, "isKeyChange", false);
        PrefUtils.setBoolean(this, "isKeyManagement",false);

        if (PrefUtils.getString(this, "cabinetCode", "").equals("")) {
            startActivity(new Intent(MainActivity.this, EditCabinetCodeActivity.class));
        } else {
            tvCabinet.setText("柜子编号:" + PrefUtils.getString(MainActivity.this, "cabinetCode", ""));
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OnOpenDeviceBtnZazNew();
                    OnIdentifyBtnZazNew();
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "请安装指纹模块", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //单机版指纹模块的destroy备份
        /*unregisterReceiver(receiver);
        EventBus.getDefault().unregister(this);
        SerialManager.getInstance().destroy();
        OnCloseDeviceBtn();
        finish();*/

        new Thread(new Runnable() {
            @Override
            public void run() {
                OnCloseDeviceBtnZazNew();
            }
        }).start();
        unregisterReceiver(receiver);
        //onKeyDown时也会走onDestroy，SerialManager没有被回收掉，而且初始化init在没有回收的情况下不会再初始化，所以在onDestroy中不需要将SerialManager.destroy掉
        //而如果onDestroy时，所有全局变量都自然回收掉了，所以再开启就算是重新初始化了，同样也不需要将SerialManager.destroy掉
        //SerialManager.getInstance().destroy();
        EventBus.getDefault().unregister(this);
        finish();
    }

    /**
     * view双击监听事件
     */
    public static class OnDoubleClickListener implements View.OnTouchListener {

        private int count = 0;//点击次数
        private long firstClick = 0;//第一次点击时间
        private long secondClick = 0;//第二次点击时间
        /**
         * 两次点击时间间隔，单位毫秒
         */
        private final int totalTime = 1000;
        /**
         * 自定义回调接口
         */
        private DoubleClickCallback mCallback;

        public interface DoubleClickCallback {
            void onDoubleClick();
        }

        public OnDoubleClickListener(DoubleClickCallback callback) {
            super();
            this.mCallback = callback;
        }

        /**
         * 触摸事件处理
         *
         * @param v
         * @param event
         * @return
         */
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEvent.ACTION_DOWN == event.getAction()) {//按下
                count++;
                if (1 == count) {
                    firstClick = System.currentTimeMillis();//记录第一次点击时间
                } else if (2 == count) {
                    secondClick = System.currentTimeMillis();//记录第二次点击时间
                    if (secondClick - firstClick < totalTime) {//判断二次点击时间间隔是否在设定的间隔时间之内
                        if (mCallback != null) {
                            mCallback.onDoubleClick();
                        }
                        count = 0;
                        firstClick = 0;
                    } else {
                        firstClick = secondClick;
                        count = 1;
                    }
                    secondClick = 0;
                }
            }
            return true;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 7777: //本地指纹识别跳转钥匙列表
                intent = new Intent(this, KeyListActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                intent.putExtra("empno", SingleUserInfoDaoImp.getInstance(ExpressApp.getInstance()).getEmpnoById(message.arg1));
                startActivity(intent);
                break;
            case 1234:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DB_Single_UserInfo db_single_userInfo = SingleUserInfoDaoImp.getInstance(MainActivity.this).getUserByEmpno(message.obj.toString());

                        if (null != db_single_userInfo && db_single_userInfo.getDepartment().equals("队长")) {
                            //如果是队长，只开大门和抽屉
                            //开大门
                            SerialManager.getInstance().getSerialHelper().sendHex(
                                    SendOrderTo485Manager.getInstance().sendTo485(
                                            "03", "01", "1a"));
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            //开抽屉
                            SerialManager.getInstance().getSerialHelper().sendHex(
                                    SendOrderTo485Manager.getInstance().sendTo485(
                                            "03", "02", "1a"));

                            //开大门开抽屉，需要设置标志位为true
                            PrefUtils.setBoolean(MainActivity.this, "isDoorOpen",true);
                            PrefUtils.setBoolean(MainActivity.this, "isDrawerOpen",true);

                            //开启报警计划
                            SerialManager.getInstance().startWarnPlan();

                            PrefUtils.setBoolean(MainActivity.this, "isCaptainOpen",true);

                        } else {
                            if (PrefUtils.getBoolean(MainActivity.this, "isCaptainOpen",false)) {
                                //队长开门之后才可以开格子

                                //改为所有人都拥有所有印章的权限，检查员取章时随机取章使用（系统判断并随机弹出）
                                /*DB_KeyInfo db_keyInfo = new DB_KeyInfo();
                                DB_KeyInfo db_keyInfo2 = new DB_KeyInfo();
                                int num = 0;
                                while (null == db_keyInfo || null == db_keyInfo2 || !db_keyInfo.getIsIn() || !db_keyInfo2.getIsIn()) {
                                    Random r = new Random();
                                    num = r.nextInt(PrefUtils.getInt(MainActivity.this, "keyNum", 0)) + 1;
                                    Log.e("屏幕", "获取印章格子随机数为：" + num);
                                    db_keyInfo = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(num);
                                    db_keyInfo2 = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(num+24);
                                }

                                if (num == 0) {
                                    Toast.makeText(MainActivity.this, "当前没有可用的印章", Toast.LENGTH_SHORT).show();
                                    return;
                                }*/

                                /*Random r = new Random();
                                int num = r.nextInt(PrefUtils.getInt(MainActivity.this, "keyNum", 0)) + 1;
                                Log.e("屏幕", "获取印章格子随机数为：" + num);*/

                                //TODO:先要判断当前日期是否跟记录的日期一致，如果不一致，则取一个随机数，记下这个随机数，并开启随机数相应的格子
                                //TODO:如果一致，则直接开启记下的随机数相应的格子
                                int num;
                                if (PrefUtils.getInt(MainActivity.this, "keyNum", 0) == 0) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(MainActivity.this, "请先进行印章初始化", Toast.LENGTH_LONG).show();
                                        }
                                    });

                                    return;
                                } else {
                                    if (PrefUtils.getString(MainActivity.this, "lastDate", "").equals("")
                                            || !PrefUtils.getString(MainActivity.this, "lastDate", "").equals(TimeUtils.getStringDateShort(new Date()))) {
                                        Random r = new Random();
                                        num = r.nextInt(PrefUtils.getInt(MainActivity.this, "keyNum", 0)) + 1;
                                        Log.e("屏幕", "获取印章格子随机数为：" + num);
                                        PrefUtils.setInt(MainActivity.this, "todayKeyNum", num);
                                        PrefUtils.setString(MainActivity.this, "lastDate", TimeUtils.getStringDateShort(new Date()));
                                    } else {
                                        num = PrefUtils.getInt(MainActivity.this, "todayKeyNum", 1);
                                    }
                                }

                                PrefUtils.setString(MainActivity.this, "uId", message.obj.toString());

                                int finalNum = num;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                                        if (null == commitDialog3 || !commitDialog3.isShowing()) {
                                            boolean isAllClosed = true;
                                            ArrayList<DB_KeyInfo> db_keyInfos = KeyInfoDaoImp.getInstance(MainActivity.this).getAllKeys();
                                            if (null != db_keyInfos) {
                                                for (int i = 0; i< db_keyInfos.size(); i++) {
                                                    //如果有不在位的，说明没有都关闭
                                                    if (db_keyInfos.get(i).getIsIn() == false) {
                                                        isAllClosed = false;
                                                    } else {
                                                        continue;
                                                    }
                                                }
                                            }
                                            if (!isAllClosed) {
                                                Toast.makeText(MainActivity.this, "还有未关闭的印章格子", Toast.LENGTH_SHORT).show();
                                                return;
                                            }

                                            showConfirmDialog3(finalNum);
                                        }
                                    }
                                });
                                /*String keyRights = SingleUserInfoDaoImp.getInstance(MainActivity.this).getKeyRightsByEmpno(message.obj.toString());
                                if (!TextUtils.isEmpty(keyRights)) {

                                    PrefUtils.setString(MainActivity.this, "uId", message.obj.toString());

                                    String[] keyNos = keyRights.split(",");
                                    for (int i = 0; i < 2; i++) {
                                        String[] ck = SendOrderTo485Manager.getInstance().getCK(Integer.parseInt(keyNos[i]));
                                        SerialManager.getInstance().getSerialHelper().sendHex(
                                                SendOrderTo485Manager.getInstance().sendTo485(
                                                        ck[0], ck[1], "1a"));

                                        //借用记录
                                        int keyNo = SendOrderTo485Manager.getInstance().getKeyNo(ck[0], Integer.parseInt(ck[1], 16));
                                        DB_KeyInfo db_keyInfo = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(keyNo);
                                        KeyInfoDaoImp.getInstance(MainActivity.this).ModifyKeyIsIn(keyNo, false);
                                        String keyName = "";
                                        if (TextUtils.isEmpty(db_keyInfo.getKeyName())) {
                                            keyName = "印章号" + db_keyInfo.getNo();
                                        } else {
                                            keyName = db_keyInfo.getKeyName();
                                        }

                                        String userName = SingleUserInfoDaoImp.getInstance(MainActivity.this).getUserByEmpno(PrefUtils.getString(MainActivity.this, "uId", "")).getUserName();
                                        KeyBorrowInfoDaoImp.getInstance(MainActivity.this).AddRecord(keyName, System.currentTimeMillis(), userName);

                                        try {
                                            Thread.sleep(500);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    //开启报警计划
                                    SerialManager.getInstance().startWarnPlan();
                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                                            if (null == commitDialog || !commitDialog.isShowing()) {
                                                showConfirmDialog("尚未设置印章权限");
                                            }
                                        }
                                    });
                                }*/
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                                        if (null == commitDialog || !commitDialog.isShowing()) {
                                            showConfirmDialog("请联系管理员");
                                        }
                                    }
                                });
                            }
                        }
                    }
                }).start();
                break;
            case 6666:
                //用户指纹验证
                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        //TODO:循环比对
                        ArrayList<DB_Single_UserInfo> db_single_userInfos = SingleUserInfoDaoImp.getInstance(MainActivity.this).getAllUsers();
                        boolean isMatch = false;
                        for (DB_Single_UserInfo db_single_userInfo : db_single_userInfos) {
                            if (null != db_single_userInfo.getFinger() && ZAZJni.fingerComparison(message.obj.toString(), db_single_userInfo.getFinger()) > 90) {
                                isMatch = true;
                                System.out.println("指纹搜索结果:"+db_single_userInfo.getEmpno());

                                //如果是队长，只开大门和抽屉
                                if (db_single_userInfo.getDepartment().equals("队长")) {
                                    //开大门
                                    SerialManager.getInstance().getSerialHelper().sendHex(
                                            SendOrderTo485Manager.getInstance().sendTo485(
                                                    "03", "01", "1a"));
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

                                    //开抽屉
                                    SerialManager.getInstance().getSerialHelper().sendHex(
                                            SendOrderTo485Manager.getInstance().sendTo485(
                                                    "03", "02", "1a"));

                                    //开大门开抽屉，需要设置标志位为true
                                    PrefUtils.setBoolean(MainActivity.this, "isDoorOpen",true);
                                    PrefUtils.setBoolean(MainActivity.this, "isDrawerOpen",true);

                                    //开启报警计划
                                    SerialManager.getInstance().startWarnPlan();

                                    PrefUtils.setBoolean(MainActivity.this, "isCaptainOpen",true);
                                } else {
                                    if (PrefUtils.getBoolean(MainActivity.this, "isCaptainOpen",false)) {
                                        //队长开门之后才可以开格子

                                        PrefUtils.setString(MainActivity.this, "uId", db_single_userInfo.getEmpno());

                                        //改为所有人都拥有所有印章的权限，检查员取章时随机取章使用（系统判断并随机弹出）
                                        /*DB_KeyInfo db_keyInfo = new DB_KeyInfo();
                                        DB_KeyInfo db_keyInfo2 = new DB_KeyInfo();
                                        int num = 0;
                                        while (null == db_keyInfo || null == db_keyInfo2 || !db_keyInfo.getIsIn() || !db_keyInfo2.getIsIn()) {
                                            Random r = new Random();
                                            num = r.nextInt(PrefUtils.getInt(MainActivity.this, "keyNum", 0)) + 1;
                                            Log.e("屏幕", "获取印章格子随机数为：" + num);
                                            db_keyInfo = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(num);
                                            db_keyInfo2 = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(num+24);
                                        }

                                        if (num == 0) {
                                            Toast.makeText(MainActivity.this, "当前没有可用的印章", Toast.LENGTH_SHORT).show();
                                            return;
                                        }*/

                                        /*Random r = new Random();
                                        int num = r.nextInt(PrefUtils.getInt(MainActivity.this, "keyNum", 0)) + 1;
                                        Log.e("屏幕", "获取印章格子随机数为：" + num);*/

                                        //TODO:先要判断当前日期是否跟记录的日期一致，如果不一致，则取一个随机数，记下这个随机数，并开启随机数相应的格子
                                        //TODO:如果一致，则直接开启记下的随机数相应的格子
                                        int num;
                                        if (PrefUtils.getInt(MainActivity.this, "keyNum", 0) == 0) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(MainActivity.this, "请先进行印章初始化", Toast.LENGTH_LONG).show();
                                                }
                                            });

                                            return;
                                        } else {
                                            if (PrefUtils.getString(MainActivity.this, "lastDate", "").equals("")
                                                    || !PrefUtils.getString(MainActivity.this, "lastDate", "").equals(TimeUtils.getStringDateShort(new Date()))) {
                                                Random r = new Random();
                                                num = r.nextInt(PrefUtils.getInt(MainActivity.this, "keyNum", 0)) + 1;
                                                Log.e("屏幕", "获取印章格子随机数为：" + num);
                                                PrefUtils.setInt(MainActivity.this, "todayKeyNum", num);
                                                PrefUtils.setString(MainActivity.this, "lastDate", TimeUtils.getStringDateShort(new Date()));
                                            } else {
                                                num = PrefUtils.getInt(MainActivity.this, "todayKeyNum", 1);
                                            }
                                        }

                                        int finalNum = num;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                                                if (null == commitDialog3 || !commitDialog3.isShowing()) {
                                                    boolean isAllClosed = true;
                                                    ArrayList<DB_KeyInfo> db_keyInfos = KeyInfoDaoImp.getInstance(MainActivity.this).getAllKeys();
                                                    if (null != db_keyInfos) {
                                                        for (int i = 0; i< db_keyInfos.size(); i++) {
                                                            //如果有不在位的，说明没有都关闭
                                                            if (db_keyInfos.get(i).getIsIn() == false) {
                                                                isAllClosed = false;
                                                            } else {
                                                                continue;
                                                            }
                                                        }
                                                    }
                                                    if (!isAllClosed) {
                                                        Toast.makeText(MainActivity.this, "还有未关闭的印章格子", Toast.LENGTH_SHORT).show();
                                                        return;
                                                    }

                                                    showConfirmDialog3(finalNum);
                                                }
                                            }
                                        });

                                        /*PrefUtils.setString(MainActivity.this, "uId", db_single_userInfo.getEmpno());
                                        String keyRights = SingleUserInfoDaoImp.getInstance(MainActivity.this).getKeyRightsByEmpno(db_single_userInfo.getEmpno());
                                        if (!TextUtils.isEmpty(keyRights)) {
                                            String[] keyNos = keyRights.split(",");
                                            for (int i = 0; i < 2; i++) {
                                                String[] ck = SendOrderTo485Manager.getInstance().getCK(Integer.parseInt(keyNos[i]));
                                                SerialManager.getInstance().getSerialHelper().sendHex(
                                                        SendOrderTo485Manager.getInstance().sendTo485(
                                                                ck[0], ck[1], "1a"));

                                                try {
                                                    Thread.sleep(500);
                                                } catch (InterruptedException e) {
                                                    e.printStackTrace();
                                                }

                                                //借用记录
                                                int keyNo = SendOrderTo485Manager.getInstance().getKeyNo(ck[0], Integer.parseInt(ck[1], 16));
                                                DB_KeyInfo db_keyInfo = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(keyNo);
                                                KeyInfoDaoImp.getInstance(MainActivity.this).ModifyKeyIsIn(keyNo, false);
                                                String keyName = "";
                                                if (TextUtils.isEmpty(db_keyInfo.getKeyName())) {
                                                    keyName = "印章号" + db_keyInfo.getNo();
                                                } else {
                                                    keyName = db_keyInfo.getKeyName();
                                                }

                                                String userName = SingleUserInfoDaoImp.getInstance(MainActivity.this).getUserByEmpno(PrefUtils.getString(MainActivity.this, "uId", "")).getUserName();
                                                KeyBorrowInfoDaoImp.getInstance(MainActivity.this).AddRecord(keyName, System.currentTimeMillis(), userName);

                                                try {
                                                    Thread.sleep(500);
                                                } catch (InterruptedException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                            //开启报警计划
                                            SerialManager.getInstance().startWarnPlan();
                                        } else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                                                    if (null == commitDialog || !commitDialog.isShowing()) {
                                                        showConfirmDialog("尚未设置印章权限");
                                                    }
                                                }
                                            });
                                        }*/
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                                                if (null == commitDialog || !commitDialog.isShowing()) {
                                                    showConfirmDialog("请联系管理员");
                                                }
                                            }
                                        });
                                    }
                                }
                            } else {
                                continue;
                            }
                        }

                        if (!isMatch) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    OtherUtil.OpenVoice10(MainActivity.this);
                                    //Toast.makeText(PwdBorrowActivity.this, msg, Toast.LENGTH_SHORT).show();
                                    if (null == commitDialog || !commitDialog.isShowing()) {
                                        showConfirmDialog("指纹识别失败，请重试");
                                    }
                                }
                            });
                        }

                        //再次搜索
                        OnIdentifyBtnZazNew();
                    }
                }).start();
                break;
            case 5555: //恢复指纹识别
                OnCloseDeviceBtnZazNew();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                OnOpenDeviceBtnZazNew();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OnIdentifyBtnZazNew();
                        } catch (Exception e) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "请安装指纹模块", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
                break;
        }
    }

    private void showConfirmDialog3(int num) {
        View view = View.inflate(this, R.layout.dialog_seal_choose, null);
        initDialogView(view, num);
        commitDialog3 = new CustomDialog(this, OtherUtil.dp2px(400), OtherUtil.dp2px(460),
                view, R.style.CustomDialog);
        commitDialog3.show();
    }

    private void initDialogView(View view, int num) {
        tv_delete = view.findViewById(R.id.tv_delete);
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog3();
            }
        });

        Timer countTimer;
        TextView tvDjs = view.findViewById(R.id.tv_djs);
        countTimer = new Timer();
        jjcount = 300;
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvDjs.setText(jjcount + "");
                    }
                });
                if (jjcount < 1) {
                    closeDialog3();
                }
            }
        }, 0, 1000);

        btn_cancel3 = view.findViewById(R.id.btn_cancel);

        btn_cancel3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] ck = SendOrderTo485Manager.getInstance().getCKOnekey(num);
                SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().sendTo485(
                                ck[0], ck[1], "1a"));

                //借用记录
                int keyNo = SendOrderTo485Manager.getInstance().getKeyNo(ck[0], Integer.parseInt(ck[1], 16));
                DB_KeyInfo db_keyInfo = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(keyNo);
                KeyInfoDaoImp.getInstance(MainActivity.this).ModifyKeyIsIn(keyNo, false);
                String keyName = "";
                if (TextUtils.isEmpty(db_keyInfo.getKeyName())) {
                    keyName = "印章号" + db_keyInfo.getNo();
                } else {
                    keyName = db_keyInfo.getKeyName();
                }

                String userName = SingleUserInfoDaoImp.getInstance(MainActivity.this).getUserByEmpno(PrefUtils.getString(MainActivity.this, "uId", "")).getUserName();
                KeyBorrowInfoDaoImp.getInstance(MainActivity.this).AddRecord(keyName, System.currentTimeMillis(), userName);

                //开启报警计划
                SerialManager.getInstance().startWarnPlan();
            }
        });

        btn_confirm3 = view.findViewById(R.id.btn_confirm);

        btn_confirm3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] ck = SendOrderTo485Manager.getInstance().getCKOnekey(num+24);
                SerialManager.getInstance().getSerialHelper().sendHex(
                        SendOrderTo485Manager.getInstance().sendTo485(
                                ck[0], ck[1], "1a"));

                //借用记录
                int keyNo = SendOrderTo485Manager.getInstance().getKeyNo(ck[0], Integer.parseInt(ck[1], 16));
                DB_KeyInfo db_keyInfo = KeyInfoDaoImp.getInstance(MainActivity.this).getKeyNameByNo(keyNo);
                KeyInfoDaoImp.getInstance(MainActivity.this).ModifyKeyIsIn(keyNo, false);
                String keyName = "";
                if (TextUtils.isEmpty(db_keyInfo.getKeyName())) {
                    keyName = "印章号" + db_keyInfo.getNo();
                } else {
                    keyName = db_keyInfo.getKeyName();
                }

                String userName = SingleUserInfoDaoImp.getInstance(MainActivity.this).getUserByEmpno(PrefUtils.getString(MainActivity.this, "uId", "")).getUserName();
                KeyBorrowInfoDaoImp.getInstance(MainActivity.this).AddRecord(keyName, System.currentTimeMillis(), userName);

                //开启报警计划
                SerialManager.getInstance().startWarnPlan();
            }
        });
    }

    private void closeDialog3() {
        if (commitDialog3 != null && commitDialog3.isShowing()) {
            commitDialog3.dismiss();
        }
    }

    private void showConfirmDialog(String hint) {
        View view = View.inflate(this, R.layout.dialog_cancel, null);
        initDialogView(view, hint);
        commitDialog = new CustomDialog(this, OtherUtil.dp2px(400), OtherUtil.dp2px(460),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initDialogView(View view, String hint) {
        TextView tvHint = view.findViewById(R.id.tv_hint);
        tvHint.setText(hint);

        /*btn_cancel = view.findViewById(R.id.btn_cancel);

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });*/

        btn_confirm = view.findViewById(R.id.btn_confirm);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }

    private void verifyFinger(String finger) {
        URL connect;
        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(Constants.urlPath + "/api/outer/user/finger/check");
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);//post不能使用缓存
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            OutputStreamWriter paramout = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8");
            String paramsStr = "";   //拼接Post 请求的参数
            paramsStr += "&" + "code" + "=" + PrefUtils.getString(this, "cabinetCode", "") + "&" + "finger" + "=" + finger;

            if (!paramsStr.isEmpty()) {
                paramsStr = paramsStr.substring(1);
            }
            Log.e("屏幕指纹", "paramsStr"+paramsStr);
            paramout.write(paramsStr);
            paramout.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }
            paramout.close();
            reader.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String result = data.toString();
        Log.e("屏幕指纹", "返回："+ result);
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.has("resultCode")) {
                String code = jsonObject.getString("resultCode");
                if (TextUtils.equals(code, "0")) {
                    String msg = jsonObject.getString("resultMsg");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                } else if (TextUtils.equals(code, "1")) {
                    String msg = jsonObject.getString("resultBody");
                    JSONObject jsonObjectContent = new JSONObject(msg);
                    String userId = jsonObjectContent.getString("userId");
                    Intent intent = new Intent(this, KeyListActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.putExtra("empno", userId);
                    startActivity(intent);

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
